const { join } = require('path')

const Table = require('cli-table')

const {
  existsSync,
  writeFileSync,
  readdirSync,
  unlinkSync,
  renameSync,
  statSync,
} = require('fs')

class Utils {
  constructor() {
    //  __dirname  获取当前文件的绝对路径
    this.folderPath = join(process.cwd(), 'src')
  }

  addFile(filename) {
    const newPath = join(this.folderPath, filename)
    // 检测该文件名是否存在
    if (existsSync(newPath)) {
      console.log('该文件已存在')
    } else {
      writeFileSync(newPath, '')
      console.log('文件创建成功')
    }
  }

  getFile() {
    return readdirSync(this.folderPath)
  }

  delFile(filename) {
    const newPath = join(this.folderPath, filename)
    unlinkSync(newPath)
    console.log('文件删除成功')
  }

  editFile({ filename, newFile }) {
    const oldPath = join(this.folderPath, filename)
    const newPath = join(this.folderPath, newFile)

    if (existsSync(newPath)) {
      console.log('文件名重复')
    } else {
      renameSync(oldPath, newPath)
      console.log('文件重命名成功')
    }
  }

  checkFile(filename) {
    const newPath = join(this.folderPath, filename)
    const { size, ctime, mtime } = statSync(newPath)
    this.createTable(size, ctime, mtime, filename)
  }
  createTable(size, ctime, mtime, filename) {
    const table = new Table({
      head: ['文件名', '文件大小', '创建时间', '修改时间'],
      colWidths: [20, 20, 40, 40],
    })
    table.push([filename, size, mtime.toLocaleString(), ctime.toLocaleString()])
    // 打印表格
    console.log(table.toString())
  }
}

module.exports = new Utils()
